package com.mike.billingserver.service.impl;

import com.mike.billingserver.constant.ApplicationConstant;
import com.mike.billingserver.dto.UserInfoDTO;
import com.mike.billingserver.service.TokenService;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;
import org.springframework.util.StringUtils;

import java.nio.charset.Charset;


/**
 * @author xiaozefeng
 * @date 2018-12-18 16:04
 */
@Service
public class TokenServiceImpl implements TokenService {

    @Override
    public UserInfoDTO validate(String token) {
        byte[] bytes = Base64Utils.decodeFromString(token);
        if (bytes == null) {
            return null;
        }
        String tokenStr = new String(bytes, Charset.forName("utf-8"));
        if (StringUtils.isEmpty(tokenStr)) {
            return null;
        }
        String[] usernameAndPassword = tokenStr.split(ApplicationConstant.TOKEN_SEPARATOR);
        UserInfoDTO userInfoDTO = new UserInfoDTO();
        userInfoDTO.setUsername(usernameAndPassword[0]);
        userInfoDTO.setPassword(usernameAndPassword[1]);
        return userInfoDTO;
    }
}
